package Reflection;

import Reflection.Po.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test_01 {


    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        User po_01 = new User("id123","name234","pwd345","text456");

        // 1.通过反射机制获取类(三种)
        Class<?> class1 ;
        class1 = po_01.getClass();
        class1 = User.class;
        class1 = Class.forName("Reflection.Po.User");

        // 2.通过获取到的类创建对象(两种)
        User po_02;

            //使用无参构造方法创建实例
        po_02 = (User) class1.newInstance();

            //获取有参构造方法
        Constructor<?> constructor = class1.getConstructor(String.class,String.class,String.class,String.class);
        po_02 = (User) constructor.newInstance("id111","name222","pwd333","text444");

        // 3.通过反射机制操作属性
        Field field = class1.getDeclaredField("name"); //通过名称获取属性
        field.setAccessible(true); //把该属性设置为可访问
        Object field_01 = field.get(po_02);//获取该类指定对象的该属性值
        System.out.println(field_01.toString());

        // 4.通过反射机制调用方法
        Method method = class1.getDeclaredMethod("getPwdByidAndName",String.class,String.class);
        method.setAccessible(true);
        Object ret = method.invoke(po_02,"id111","name222");
        System.out.println(ret.toString());

    }

}
